package code.oldCode.dynamic;

public class LongestCommonSubsequence {

    /**
     * 1143. 最长公共子序列
     * @param text1
     * @param text2
     * @return
     */
    public int longestCommonSubsequence(String text1, String text2) {
        int len1 = text1.length();
        int len2 = text2.length();
        char[] s1 = text1.toCharArray();
        char[] s2 = text2.toCharArray();
        int[][] dp = new int[len1][len2];

        for (int i = 0; i < len1; i++) {
            for (int j = 0; j < len2; j++) {
                if (i == 0 && j == 0)
                    dp[0][0] = s1[0] == s2[0] ? 1 : 0;
                else if (i == 0) {
                    if (s1[i] == s2[j])
                        dp[i][j] = 1;
                    else
                        dp[i][j] = dp[i][j - 1];
                }
                else if (j == 0) {
                    if (s1[i] == s2[j])
                        dp[i][j] = 1;
                    else
                        dp[i][j] = dp[i - 1][j];
                }
                else {
                    if (s1[i] == s2[j])
                        dp[i][j] = dp[i - 1][j - 1] + 1;
                    else
                        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[len1 - 1][len2 - 1];
    }

    /**
     * 1035. 不相交的线
     * @param nums1
     * @param nums2
     * @return
     */
    public int maxUncrossedLines(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        int[][] dp = new int[len1][len2];
        for (int i = 0; i < len1; i++) {
            for (int j = 0; j < len2; j++) {
                if (i == 0 && j == 0)
                    dp[i][j] = nums1[i] == nums2[j] ? 1 : 0;
                else if (i == 0)
                    dp[i][j] = nums1[i] == nums2[j] ? 1 : dp[i][j - 1];
                else if (j == 0)
                    dp[i][j] = nums1[i] == nums2[j] ? 1 : dp[i - 1][j];
                else
                    dp[i][j] = nums1[i] == nums2[j] ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
            }
        }

        return dp[len1 - 1][len2 - 1];
    }

    public static void main(String[] args) {

    }
}
